﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Threading;
using Application = System.Windows.Application;

namespace WqReminderTool
{
    /// <summary>
    ///     App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private bool _onShow = false;
        private List<Window> _onShowWindows = new List<Window>();

        protected override void OnStartup(StartupEventArgs e)
        {
            var dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
            // 立即调用一次Tick事件处理函数
            dispatcherTimer_Tick(dispatcherTimer, new EventArgs());
            dispatcherTimer.Start();
            base.OnStartup(e);
        }

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            if (_onShow)
            {
                return;
            }
            if (DateTime.Now.Minute == 50 && (DateTime.Now.Second == 0 || DateTime.Now.Second == 1))
            {
                //  显示多个显示器底代码，当设置为DPI缩放时，会出现显示不全的问题
                int count = Screen.AllScreens.Length;
                if (count > 0)
                {
                    _onShow = true;
                    foreach (var screen in Screen.AllScreens)
                    {
                        ShowTipOnScreen(screen);
                    }
                }
            }
        }

        public void CloseAllShowWindow()
        {
            _onShow = false;
            if (_onShowWindows.Count > 0)
            {
                foreach (var window in _onShowWindows)
                {
                    if (window.IsVisible)
                    {
                        window.Close();
                    }
                }
                _onShowWindows.Clear();
            }
        }

        private void ShowTipOnScreen(Screen screen)
        {
            NotifyWindow window = new NotifyWindow();
            window.App = this;

            // 获取DPI缩放比例
            using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
            {
                float dpiX = g.DpiX / 96.0f;
                float dpiY = g.DpiY / 96.0f;

                window.Left = screen.Bounds.X / dpiX;
                window.Top = screen.Bounds.Y / dpiY;
                window.Width = screen.Bounds.Width / dpiX;
                window.Height = screen.Bounds.Height / dpiY;
            }

            window.Show();
            _onShowWindows.Add(window);
        }
    }
}